/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package io.simple.core;


import injections.annotations.Property;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException;

/**
 *
 * @author rehak
 */
public class SSLContextFactory {

    @Property(optional = true)
    private String algorithm = "SunX509";
    @Property
    private String keystorePath;
    @Property
    private String keystorePassword;
    @Property(optional = true)
    private String protocol = "TLS";
    @Property(optional = true)
    private String keystoreType = "PKCS12"; // can also be "JKS" - java key store

    public SSLContextFactory() {
        this.algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
    }

    public SSLContext getInstance() throws Exception {
        SSLContext serverContext = null;
        try {

            KeyStore ks = KeyStore.getInstance(keystoreType);
            FileInputStream fin = new FileInputStream(keystorePath);
            ks.load(fin, keystorePassword.toCharArray());

            // Set up key manager factory to use our key store
            // Assume key password is the same as the key store file
            // password
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
            kmf.init(ks, keystorePassword.toCharArray());

            // Initialise the SSLContext to work with our key managers.
            serverContext = SSLContext.getInstance(protocol);
            serverContext.init(kmf.getKeyManagers(), null, null);
        } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException | KeyManagementException e) {
            throw new Error("Failed to initialize the server-side SSLContext", e);
        }
        return serverContext;
    }
}
